package cn.yzgy.yzgyoa.common.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;

/**
 * <p>IP工具类，获取客户端真实IP</p>
 *
 * @author Yqsen
 * @version 0.0.1
 */
public class IpUtil {

    private static final String UNKNOWN_STRING = "unknown";
    private static final String X_FORWARDED_FOR_STRING = "x-forwarded-for";
    private static final String PROXY_CLIENT_IP_STRING = "Proxy-Client-IP";
    private static final String WL_PROXY_CLIENT_IP_STRING = "WL-Proxy-Client-IP";
    private static final String LOCALHOST_IP = "127.0.0.1";
    private static final int MAX_IP_STRING_LENGTH = 15;
    private static final String IP_ADDRESS_SPLIT_CHARACTER = ",";


    /**
     * 判断目前获取到ip地址是否有效
     *
     * @param ipAddress ip地址
     * @return true false
     */
    private static boolean ipAddressNotValid(String ipAddress) {
        return (ipAddress == null || ipAddress.length() == 0 || UNKNOWN_STRING.equalsIgnoreCase(ipAddress));
    }

    public static boolean internalIp(String ip) {
        byte[] addr = textToNumericFormatV4(ip);
        return internalIp(addr);
    }

    public static byte[] textToNumericFormatV4(String text) {
        byte[] emptyByte = new byte[0];
        if (text.length() == 0) {
            return emptyByte;
        }

        byte[] bytes = new byte[4];
        String[] elements = text.split("\\.", -1);
        try {
            long l;
            int i;
            switch (elements.length) {
                case 1:
                    l = Long.parseLong(elements[0]);
                    if ((l < 0L) || (l > 4294967295L)) {
                        return emptyByte;
                    }
                    bytes[0] = (byte) (int) (l >> 24 & 0xFF);
                    bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 2:
                    l = Integer.parseInt(elements[0]);
                    if ((l < 0L) || (l > 255L)) {
                        return emptyByte;
                    }
                    bytes[0] = (byte) (int) (l & 0xFF);
                    l = Integer.parseInt(elements[1]);
                    if ((l < 0L) || (l > 16777215L)) {
                        return emptyByte;
                    }
                    bytes[1] = (byte) (int) (l >> 16 & 0xFF);
                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 3:
                    for (i = 0; i < 2; ++i) {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > 255L)) {
                            return emptyByte;
                        }
                        bytes[i] = (byte) (int) (l & 0xFF);
                    }
                    l = Integer.parseInt(elements[2]);
                    if ((l < 0L) || (l > 65535L)) {
                        return emptyByte;
                    }
                    bytes[2] = (byte) (int) (l >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 4:
                    for (i = 0; i < 4; ++i) {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > 255L)) {
                            return emptyByte;
                        }
                        bytes[i] = (byte) (int) (l & 0xFF);
                    }
                    break;
                default:
                    return emptyByte;
            }
        } catch (NumberFormatException e) {
            return emptyByte;
        }
        return bytes;
    }


    public static boolean internalIp(byte[] addr) {
        final byte b0 = addr[0];
        final byte b1 = addr[1];
        //10.x.x.x/8
        final byte SECTION_1 = 0x0A;
        //172.16.x.x/12
        final byte SECTION_2 = (byte) 0xAC;
        final byte SECTION_3 = (byte) 0x10;
        final byte SECTION_4 = (byte) 0x1F;
        //192.168.x.x/16
        final byte SECTION_5 = (byte) 0xC0;
        final byte SECTION_6 = (byte) 0xA8;
        switch (b0) {
            case SECTION_1:
                return true;
            case SECTION_2:
                if (b1 >= SECTION_3 && b1 <= SECTION_4) {
                    return true;
                }
            case SECTION_5:
                if (b1 == SECTION_6) {
                    return true;
                }
            default:
                return false;
        }
    }

    /**
     * 获取用户访问的真实？IP地址
     *
     * @param request httpServletRequest
     * @return IP地址或 空
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress;

        try {
            ipAddress = request.getHeader(X_FORWARDED_FOR_STRING);
            if (ipAddressNotValid(ipAddress)) {
                ipAddress = request.getHeader(PROXY_CLIENT_IP_STRING);
            }
            if (ipAddressNotValid(ipAddress)) {
                ipAddress = request.getHeader(WL_PROXY_CLIENT_IP_STRING);
            }
            if (ipAddressNotValid(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (LOCALHOST_IP.equals(ipAddress)) {
                    // 根据网卡取本机配置的IP
                    InetAddress inetAddress = null;
                    try {
                        inetAddress = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = Objects.requireNonNull(inetAddress).getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > MAX_IP_STRING_LENGTH) {
                // = 15
                if (ipAddress.indexOf(IP_ADDRESS_SPLIT_CHARACTER) > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(IP_ADDRESS_SPLIT_CHARACTER));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }

        return ipAddress;
    }
}
